<?php

namespace app\admin\controller\merchant;

use app\common\controller\Backend;
use think\Db;
use think\Session;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\merchant\Order
     */
    protected $model = null;
    protected $order_goods_model = null;
    protected $user_model = null;
    protected $staff_model = null;
    const state_txt=[1=>'待支付',2=>'待发货',3=>'待收货',4=>'待评论',5=>'售后订单',6=>'已完成',7=>'已取消'
        ,8=>'退款列表',9=>'退款状态',10=>'退款失败',11=>'退款成功',12=>'退款中',13=>'取消退款'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\merchant\Order;
        //$this->order_goods_model = new \app\admin\model\merchant\Ordergoods;
        $this->order_goods_model = new \app\admin\model\order\Goods;
        $this->user_model = new \app\admin\model\User;
        $this->staff_model = new \app\admin\model\Staff;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("ontypeList", $this->model->getOntypeList());
        $this->view->assign("issupplementList", $this->model->getIssupplementList());
    }

    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $_where['b_shop_id'] = ['<>',0];
            if ($this->request->get("user_id")) {
                $_where['order.user_id'] = $this->request->get("user_id");
            }
            //当前管理员店铺id
            $_admin = Session::get('adminshop');
            //当前店铺id
            $shop_id = Session::get('shop');
            $defaultWhere=[];
            $defaultWhere['data_type']='merchant';

            if($_admin==1 && $shop_id != 1){
                $defaultWhere['b_shop_id']= $shop_id;
            }elseif($_admin !=1){
                $defaultWhere['b_shop_id']= $_admin;
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //print_r($where);
            $list = $this->model
                ->with('bshop,pay,user,address')
                ->where($where)
                ->where($_where)
                ->where($defaultWhere)
                ->order($sort, $order)
                ->paginate($limit);
            //print_r($this->model->getLastSql());exit;
            $total = $list->total();

            $rows = $list->items();

            foreach ($rows as &$val) {
                if (is_null($val['user_id'])) {
                    unset($rows[$key]);
                    continue;
                }
                if (!empty($val['remarks'])) {
                    $remarks = mb_substr(strip_tags($val['remarks']), 0, 15, "UTF-8").'......';
                    $val['order_no'] .= ',备注:'.$remarks;
                }
                $goods = $this->order_goods_model->where(['order_id'=>$val['id']])->select();
                $tmp=[];
                if($goods){
                    foreach ($goods as $v) {
                        $title = mb_substr(strip_tags($v['title']), 0, 20, "UTF-8").'......';
                        $tmp[]="名称：".$title ." 价格：".$v['actual_payment'].",";
                    }
                }
                $val['goods_name'] = join(',',$tmp);

                //$orderinfo = $this->order_model->where(['id'=>$val['id']])->find();
                $userinfo = $this->user_model->where(['id'=>$val['user_id']])->find();
                $val['nickname'] = '';
                $val['address_detail']='';

                if ($val['user_id'] != null) {
                    $userinfo = $this->user_model->where(['id'=>$val['user_id']])->find();
                    $val['nickname'] = !empty($userinfo)?$userinfo['nickname']:'';
                    $val['address_detail']=mb_substr($val['address']['province'].$val['address']['city'].$val['address']['district'].$val['address']['formatted_address'], 0, 10, "UTF-8").'......';
                }
                

            }
            // print_r($rows);die;
            //echo 33333;exit;
            $result = array("total" => $total, "rows" => $rows);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        $row['state_txt'] = self::state_txt[$row['state']]??"";
        $address = Db::name('wanlshop_order_address')
            ->where(['order_id' => $row['id']])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();
        $row['address'] =$address['address'] ??"";
        $row['pay'] = Db::name('wanlshop_pay')
            ->where(['order_id' => $row['id'], 'type' => 'goods'])
            ->find();
        $row['shop'] = Db::name('wanlshop_shop')
            ->where(['id' => $row['shop_id']])
            ->find();

        $row['user'] = Db::name('user')
            ->where(['id' => $row['user_id']])
            ->field('id,nickname,username,mobile')
            ->find();
        $couponPrice=0;
        if($row['coupon_id']){
            $coupon = Db::name('wanlshop_coupon_receive')
                ->where(['order_id' => $row['id']])
                ->find();
            $couponPrice= sprintf('%.2f',$coupon['price']);
        }
        $this->view->assign("couponPrice", $couponPrice);
        $info = Db::name('wanlshop_order_goods')
            ->where(['order_id' =>  $row['id']])
            ->select();

        if($info){
            foreach ($info as &$value){


            }

        }
        $row['info']=$info;

        $row['pay_way'] = '余额支付';
        if ($row['pay']['pay_type']) {
            switch ($row['pay']['pay_type']) {
                case '1':
                    $row['pay_way'] = '微信支付';
                    break;
                case '2':
                    $row['pay_way'] = '支付宝支付';
                    break;
                case '3':
                    $row['pay_way'] = '对公转账';
                    break;
                default:
                    $row['pay_way'] = '余额支付';
                    break;
            }
        }
        $goodsCount = count($row['info']);
        $this->view->assign("goodsCount", $goodsCount);
        $payTime = isset($row['paymenttime']) ? date('Y-m-d H:i:s',$row['paymenttime']):"";
        $this->view->assign("payTime", $payTime);


        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        //print_r($row);exit;
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);

            return $this->view->fetch();
        }

    }

    public function change_order(){
        $param =$this->request->param();
        if($param['order_id']){
            $order = Db::name('wanlshop_order')->where(['id'=>$param['order_id']])->find();
            switch ($order['state']){
                case 2:
                    if($param['express_name'] && $param['express_no']){
                        $update=[];
                        $update['express_name'] = $param['express_name'];
                        $update['express_no'] = trim($param['express_no']);
                        $update['updatetime'] = time();
                        $update['state'] = 3;
                        $update['delivertime'] = time(); //发货时间
                        if(Db::name('wanlshop_order')->where(['id'=>$param['order_id']])->update($update)){
                            $this->success("发货成功",url('merchant/order'));
                        }else{
                            $this->error("发货失败");
                        }
                    }
                    break;
            }
        }
        $this->error("操作失败");

    }


}
